<%@ page pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<!DOCTYPE html >
<html>
<head>
    <base href="${base}/"/>
    <title>后台管理</title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" href="css/admin.css"/>
    <link rel="stylesheet" href="css/zTreeStyle/zTreeStyle.css" type="text/css">
    <script type="text/javascript" src="/js/jquery-3.7.1.min.js"></script>
    <script type="text/javascript" src="/js/jquery.ztree.all.min.js"></script>
    <script type="text/javascript">
        $(function () {
            const setting = {
                check: {
                    enable: false,
                    chkStyle: "radio",
                    radioType: 'all'
                },
                view: {
                    dblClickExpand: false
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: onClick,
                    //onCheck: onCheck
                }
            };

            function onClick(e, treeId, treeNode) {
                $("#pname").attr("value", treeNode.name);
                $("#pid").attr("value", treeNode.id);
                $("#menuContent").fadeOut("fast");
                $("body").unbind("mousedown", onBodyDown);
            }


            function showCategories() {
                var cityObj = $("#pname");
                var cityOffset = $("#pname").offset();
                $("#menuContent").css({
                    left: cityOffset.left + "px",
                    top: cityOffset.top + cityObj.outerHeight() + "px"
                }).slideDown("fast");

                $("body").bind("mousedown", onBodyDown);
            }

            function hideMenu() {
                $("#menuContent").fadeOut("fast");
                $("body").unbind("mousedown", onBodyDown);
            }

            function onBodyDown(event) {
                if (!(event.target.id == "menuBtn" || event.target.id == "pname" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length > 0)) {
                    hideMenu();
                }
            }

            $(function () {
                $.fn.zTree.init($("#treeDemo"), setting, ${categories});
            });

            // 表单提交前的验证
            $('form').on('submit', function(e) {
                e.preventDefault();
                
                // 获取表单数据
                var name = $('input[name="name"]').val();
                var no = $('input[name="no"]').val();
                var categoryId = $('select[name="categoryId"]').val();
                var stock = $('input[name="stock"]').val();
                var marketPrice = $('input[name="marketPrice"]').val();
                var salePrice = $('input[name="salePrice"]').val();
                var description = $('#description').val();
                
                // 验证必填字段
                if (!name || !no || !categoryId || !stock || !marketPrice || !salePrice) {
                    alert('请填写所有必填字段！');
                    return false;
                }
                
                // 验证价格
                if (parseFloat(salePrice) > parseFloat(marketPrice)) {
                    alert('销售价格不能高于市场价格！');
                    return false;
                }
                
                // 验证库存
                if (parseInt(stock) < 0) {
                    alert('库存不能为负数！');
                    return false;
                }
                
                // 验证商品编号格式
                if (!/^[A-Za-z0-9]+$/.test(no)) {
                    alert('商品编号只能包含字母和数字！');
                    return false;
                }
                
                // 如果验证通过，提交表单
                this.submit();
            });
            
            // 图片上传预览
            $('#uploadInput').on('change', function() {
                var file = this.files[0];
                if (file) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        $('#showImage').attr('src', e.target.result);
                    }
                    reader.readAsDataURL(file);
                }
            });
        })
        $(function (){
            let selectedFiles = [];
            let inputId = "uploadInput";
            let imgId = "showImage";
            let fileInput = $('#'+inputId);
            // 上传文件点击事件，选择文件之后就开始上传
            fileInput.on('change', function() {
                if (this.files.length > 0) {
                    handleFiles(this.files);
                }
            });
            function handleFiles(files) {
                for (let i = 0; i < files.length; i++) {
                    const file = files[i];

                    // 检查是否是图片
                    if (!file.type.startsWith('image/')) {
                        continue;
                    }

                    // 检查文件是否已存在
                    let isDuplicate = false;
                    for (let j = 0; j < selectedFiles.length; j++) {
                        if (selectedFiles[j].name === file.name &&
                            selectedFiles[j].size === file.size &&
                            selectedFiles[j].lastModified === file.lastModified) {
                            isDuplicate = true;
                            break;
                        }
                    }

                    if (!isDuplicate) {
                        selectedFiles.push(file);
                    }
                }
                //上传图片
                if(selectedFiles.length>0){
                    for (let i = 0; i < selectedFiles.length; i++) {
                        uploadFile(selectedFiles[i]);
                    }
                }
            }

            // 上传单个文件
            function uploadFile(file, callback) {
                const formData = new FormData();
                formData.append('file', file);
                $.ajax({
                    url: '/admin/upload/goods',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        console.log(response);
                        $('#'+imgId).attr("src",response);
                        // 添加一个隐藏的input来保存图片URL
                        if($('#imageUrl').length === 0) {
                            $('<input>').attr({
                                type: 'hidden',
                                id: 'imageUrl',
                                name: 'image',
                                value: response
                            }).appendTo('form');
                        } else {
                            $('#imageUrl').val(response);
                        }
                    },
                    error: function(xhr) {
                        alert("上传文件失败");
                    },
                    complete: function() {
                        if (callback) callback();
                    }
                });
            }
        })
    </script>
</head>
<body>
<div class="container">
    <div id="header">
        <div class="logo">
            <a href=""><img src="images/admin/logo.png" width="303" height="43" /></a>
        </div>
        <p>
            <a href="/admin/logout">退出管理</a> <a href="/admin">后台首页</a> <a href="/" target='_blank'>商城首页</a>
            <span>您好 <label class='bold'>${sessionScope.manager.account}</label></span>
        </p>
    </div>
    <div id="admin_left">
        <ul class="submenu">
            <ul class="menu">
                <li><a href="admin/category/add">增加类别</a></li>
                <li><a href="admin/category/list">类别列表</a></li>
                <li><a href="admin/goods/add">增加商品</a></li>
                <li><a href="admin/goods/list">商品列表</a></li>
                <li><a href="admin/user/list">用户列表</a></li>
            </ul>
        </ul>
        <div id="copyright"></div>
    </div>

    <div id="admin_right">
        <div class="content_box">
            <div class="content form_content">
                <form action="/admin/goods/add" method="post" enctype="multipart/form-data">
                    <div id="table_box_1">
                        <table class="form_table">
                            <colgroup>
                                <col width="150px">
                                <col>
                            </colgroup>
                            <tbody>
                            <tr>
                                <th>商品名称：</th>
                                <td><input class="normal" name="name" type="text" required
                                           placeholder="请输入商品名称"><label class="required">*</label></td>
                            </tr>
                            <tr>
                                <th>商品编号：</th>
                                <td><input class="normal" name="no" type="text" required
                                           placeholder="请输入商品编号"><label class="required">*</label></td>
                            </tr>
                            <tr>
                                <th>所属分类：</th>
                                <td>
                                    <select name="categoryId" required>
                                        <option value="">请选择分类</option>
                                        <c:forEach items="${categories}" var="category">
                                            <option value="${category.id}">${category.name}</option>
                                        </c:forEach>
                                    </select>
                                    <label class="required">*</label>
                                </td>
                            </tr>
                            <tr>
                                <th>基本数据：</th>
                                <td>
                                    <div class="con">
                                        <table class="border_table">
                                            <thead id="goodsBaseHead">
                                            <tr>
                                                <th>库存</th>
                                                <th>市场价格</th>
                                                <th>销售价格</th>
                                            </tr>
                                            </thead>
                                            <tbody id="goodsBaseBody">
                                            <tr class="td_c">
                                                <td>
                                                    <input class="tiny" name="stock" type="number" min="0" required
                                                           placeholder="库存数量">
                                                    <label class="required">*</label>
                                                </td>
                                                <td>
                                                    <input class="tiny" name="marketPrice" type="number" step="0.01" min="0" required
                                                           placeholder="市场价格">
                                                    <label class="required">*</label>
                                                </td>
                                                <td>
                                                    <input class="tiny" name="salePrice" type="number" step="0.01" min="0" required
                                                           placeholder="销售价格">
                                                    <label class="required">*</label>
                                                </td>
                                            </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <th>商品图片：</th>
                                <td><input type="file" name="file" id="uploadInput"/>
                                    <img src="..." id="showImage" width="50" height="50">
                                </td>
                            </tr>
                            <tr>
                                <th>商品描述：</th>
                                <td>
                                    <textarea rows="5" cols="50" name="description" id="description" 
                                              placeholder="请输入商品详细描述"></textarea>
                                </td>
                            </tr>
                            <tr>
                                <th>商品属性：</th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="hottest" value="Y"/>
                                        设为热卖商品
                                    </label>
                                    <label style="margin-left: 20px;">
                                        <input type="checkbox" name="newest" value="Y"/>
                                        设为最新商品
                                    </label>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="form_buttons">
                        <button type="submit" class="submit">
                            <span>发布商品</span>
                        </button>
                        <button type="reset" class="reset">
                            <span>重置</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div id="separator"></div>
</div>
</body>
</html>